<template>
  <div ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts/core'
import 'echarts-wordcloud'
import { TooltipComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([TooltipComponent, CanvasRenderer])

const props = defineProps({
  words: {
    type: Array,
    required: true
  }
})

const chartRef = ref(null)
let chartInstance = null

const renderChart = () => {
  if (!chartRef.value) return
  chartInstance = echarts.init(chartRef.value)
  const option = {
    tooltip: {},
    series: [{
      type: 'wordCloud',
      gridSize: 8,
      sizeRange: [12, 50],
      rotationRange: [-45, 90],
      shape: 'circle',
      width: '100%',
      height: '100%',
      drawOutOfBound: true,
      textStyle: {
        color: () => {
          return `rgb(${[
            Math.round(Math.random() * 160),
            Math.round(Math.random() * 160),
            Math.round(Math.random() * 160)
          ].join(',')})`
        }
      },
      data: props.words
    }]
  }
  chartInstance.setOption(option)
}

watch(() => props.words, () => {
  if (chartInstance) {
    chartInstance.setOption({
      series: [{ data: props.words }]
    })
  } else {
    renderChart()
  }
})

onMounted(() => {
  renderChart()
})
</script>
